from flask import request, abort
from app.utils.jwt_utils import decode_token
import fnmatch

# 定义不需要校验 token 的路由
WHITELIST_ROUTES = [
    "/api/auth/register",
    "/api/auth/login",
    "/",
    "/swaggerui/*",
    "/favicon.ico",
    "/swagger.json",
    "/swagger.yaml",
    "/api/swagger.json"
]


def auth_middleware():
    # 获取当前请求的路径
    path = request.path

    # 检查请求路径是否在白名单中
    if any(fnmatch.fnmatch(path, pattern) for pattern in WHITELIST_ROUTES):
        return None

    # 获取请求头中的 Authorization 字段
    token = request.headers.get('Authorization')
    if not token or not token.startswith('JWT '):
        abort(401, description='无效的令牌')

    token = token.split(' ')[1]
    payload = decode_token(token)
    if not payload:
        abort(401, description='令牌无效或已过期')

    # 将 user_id 存入 request 对象
    request.user_id = payload['user_id']
